package com.ccc.netty.server.base;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.SocketAddress;

/**
 *
 *      Netty自定义处理器，继承ChannelInboundHandlerAdapter。
 *       用于处理入站I/O事件——接收数据
 *
 *  Sharable注解： netty注解， 被Sharable注解，全局只有一个handler实例,它会被多个Channel的Pipeline共享
 *
 *
 * @author superC
 * @version 1.0.0
 * @date 2022/7/7
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class MyHandler extends ChannelInboundHandlerAdapter {

    @Override
    // 客户端与服务器端建立连接
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketAddress remoteIp = ctx.channel().remoteAddress();
        log.info("与客户端建立连接,ctx={},ip={}", ctx, remoteIp);
    }

    @Override
    // 接收客户端发送的消息
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("接收到的消息为----- {}", msg);
    }

    @Override
    // 接收客户端发送的消息完毕
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        try {
            ctx.flush();
        } catch (Exception e) {
        }
    }

    // 断开连接
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            log.info("终端断开连接,ctx={}", ctx);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    @Override
    // 程序异常
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        try {
            log.info("程序异常,ctx={}", ctx);
            ctx.close();
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        log.error(cause.getMessage(), cause);
    }
}